import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPSeverPlus {
    private ServerSocket listenSocket = null;
    public TCPSeverPlus(int pork) throws IOException {
        listenSocket = new ServerSocket(9999);
    }
    private void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            Socket clientSocket = listenSocket.accept();
            Thread thread = new Thread(){
                @Override
                public void run() {
                    process(clientSocket);
                }
            };
            thread.start();
        }
    }
    private void process(Socket clientSocket){
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            String log = String.format("[%s:%d]客户端上线",clientSocket.getInetAddress().toString(),
                                               clientSocket.getPort());
            System.out.println(log);
            while (true) {
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()){
                    log = String.format("[%s:%d]客户端下线",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    System.out.println(log);
                    break;
                }
                String request = scanner.next();
                String response = responseFun(request);
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                log = String.format("[%s:%d],%s,%s",clientSocket.getInetAddress().toString(),
                                           clientSocket.getPort(),request,response);
                System.out.println(log);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private String responseFun(String request) {
        return request + "嘎嘎";
    }

    public static void main(String[] args) throws IOException {
        TCPSeverPlus tcpSeverPlus = new TCPSeverPlus(9999);
        tcpSeverPlus.start();
    }
}
